<template>
  <div class="item-prop">
    <el-row gutter="20">
      <el-col span="24">
        <el-card class="sur-card">
          <el-divider>基本信息</el-divider>
          <div class="sur-card-title" slot="header">
            <span>编辑定制属性</span>
          </div>
          <el-form :model="itemModel" label-position="left" label-width="120px">
            <el-form-item label="商品标题">
              <el-input
                v-model="itemModel.itemName"
                style="width: 450px;"
                maxlength="55"
                show-word-limit
                placeholder="请输入产品名称"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品编码">
              <el-input
                style="width: 450px;"
                readonly
                v-model="itemModel.itemCode"
                placeHolder="请输入商品编码"
                maxlength="55"
                show-word-limit
              ></el-input>
            </el-form-item>
            <el-form-item label="主图">
              <el-upload
                style="display: inline-block;"
                :http-request="handleMainImgUploadFile"
                :show-file-list="false"
              >
                <el-button size="small" type="primary" icon="el-icon-picture"
                  >点击上传</el-button
                >
              </el-upload>
              <hover-mask v-if="itemModel.mainImage">
                <!-- 默认插槽 -->
                <el-image
                  :src="itemModel.mainImage"
                  fit="contain"
                  style="height: 80px;width: 80px;"
                ></el-image>
                <!-- action插槽 -->
                <template v-slot:action>
                  <i class="el-icon-delete" @click="onDeleteMainImage"></i>
                </template>
              </hover-mask>
            </el-form-item>
            <el-form-item label="轮播素材">
              <el-button
                size="small"
                icon="el-icon-edit"
                @click="onEditCarouseMedia"
                >编辑素材</el-button
              >
            </el-form-item>
            <div style="text-align: center;">
              <el-button
                style="width: 280px;margin-top: 22px;"
                type="danger"
                size="medium"
                @click="onSaveItem"
                >保存基础信息</el-button
              >
            </div>
          </el-form>
          <div v-if="itemModel.id">
            <el-divider>规格信息</el-divider>
            <!--    规格编辑开始-->
            <vue-sku
              v-if="showSkuEditor"
              v-model="specOptions"
              :sku-tree="specNames"
              :on-fetch-group="fetchSkuGroup"
              :on-fetch-sku="fetchSku"
              :on-create-group="createGroup"
              :on-create-sku="createSku"
              @on-change="onSkuChange"
            />
            <br />
            <sku-table
              :data="specOptions"
              :flatten="skuList"
              :itemCode="'DIY_TABLET_MUFF'"
              @on-change-data="handleChangeData"
            >
            </sku-table>
            <div style="text-align: center;">
              <el-button
                style="width: 280px;margin-top: 22px;"
                type="danger"
                size="medium"
                @click="onSaveSkuList"
                >保存规格信息</el-button
              >
            </div>
            <!--    规格编辑结束-->
          </div>

          <div v-if="itemModel.id">
            <el-divider>图文详情</el-divider>
            <el-row type="flex" justify="center">
              <el-col span="20">
                <h-editor
                  v-if="showEditor"
                  @change="onInputChange"
                  :initContent="itemDesc.descText"
                ></h-editor>
              </el-col>
            </el-row>
            <div style="text-align: center;">
              <el-button
                style="width: 280px;margin-top: 22px;"
                type="danger"
                size="medium"
                @click="onSaveItemDesc"
                >保存图文详情</el-button
              >
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <item-media-editor
      :show.sync="editCarouselMedia"
      :carousel-medias="itemModel.carouselMedias"
      v-on:onCarouseMediaSaved="onCarouseMediaSaved"
    ></item-media-editor>
  </div>
</template>

<script>
import { addItem, updateItemById } from "@/api/admin-api/ItemApi";
import { listAllCategory } from "@/api/admin-api/CagegoryApi";
import {
  getUploadItemMediaToken,
  uploadFileToAliOss
} from "@/api/admin-api/FileApi";
import { getItemDetail } from "@/api/admin-api/DiyTabletMuffApi";
import { getItemSkuList, mergeItemSkus } from "@/api/admin-api/ItemSkuApi";
import {
  addItemSpec,
  addSpecProps,
  getItemSpecList,
  getSpecProps
} from "@/api/admin-api/SpecApi";
import { Sku, SkuTable } from "@/components/Sku";
import {
  getItemDesc,
  saveItemDesc,
  updateItemDesc
} from "@/api/admin-api/ItemDescApi";
import HEditor from "@/components/HEditor";
import ItemMediaEditor from "@/components/ItemProp/ItemMediaEditor";

export default {
  name: "DiyEarMuffItemProp",
  components: {
    "vue-sku": Sku,
    "sku-table": SkuTable,
    HEditor,
    ItemMediaEditor
  },
  data() {
    return {
      categories: [],
      editCarouselMedia: false,
      itemModel: {
        catId: null,
        onSale: false,
        itemName: null,
        itemCode: "DIY_TABLET_MUFF",
        caption: null,
        keywords: null,
        mainImage: null,
        carouselMedias: [],
        carouselMediasJson: "[]",
        itemType: null,
        tags: null,
        visitedNum: null,
        sort: null
      },
      showSkuEditor: false, //是否显示sku编辑器，防止数据延迟
      specNames: [], //规格名列表
      specOptions: [], // 规格和选项列表
      data: [],
      skuList: [],
      showEditor: false,
      itemDesc: {
        itemId: "",
        id: "",
        descText: ""
      }
    };
  },
  methods: {
    onSaveItem() {
      this.$loading();
      if (this.itemModel.id) {
        // 更新
        updateItemById(this.itemModel).then(() => {
          this.$message.success("保存成功");
          this.loadBasicItem();
          this.$loading().close();
        });
      } else {
        // 保存新的
        addItem(this.itemModel).then(() => {
          this.$loading().close();
          this.$message.success("保存成功");
          this.$router.back();
        });
      }
      //保存商品信息
      console.log("this.itemModel", this.itemModel);
    },
    onCarouseMediaSaved(mediaJson) {
      console.log(mediaJson);
      this.itemModel.carouselMediasJson = mediaJson;
    },
    onDeleteMedia(row) {
      console.log(row);
    },
    onEditCarouseMedia() {
      console.log(
        "JSON.parse(this.carouselMediasJson)",
        this.itemModel.carouselMediasJson
      );
      this.itemModel.carouselMedias = JSON.parse(
        this.itemModel.carouselMediasJson
      );
      this.editCarouselMedia = true;
    },
    onDeleteMainImage() {
      this.itemModel.mainImage = "";
    },
    loadAllCategories() {
      return new Promise(resolve => {
        listAllCategory().then(data => {
          // this.categories = data.records;
          resolve(data.records);
        });
      });
    },
    handleMainImgUploadFile({ file }) {
      getUploadItemMediaToken().then(uploadToken => {
        // 上传文件
        const formData = new FormData();
        const fileKey = uploadToken.dir.concat(file.name);
        formData.append("key", fileKey);
        formData.append("policy", uploadToken.policy);
        formData.append("OSSAccessKeyId", uploadToken.ossAccessKeyId);
        formData.append("success_action_status", "200");
        formData.append("signature", uploadToken.signature);
        formData.append("file", file);
        // 上传至阿里云oss
        this.$loading();
        console.log("上传地址", uploadToken.fileHost);
        uploadFileToAliOss(uploadToken.fileHost, formData)
          .then(() => {
            this.itemModel.mainImage = "https://asset.fanghaowu.com/" + fileKey;
            this.$loading().close();
          })
          .catch(() => {
            this.$loading().close();
          });
      });
    },
    loadBasicItem() {
      getItemDetail().then(data => {
        if (data) {
          this.itemModel = data;
          this.itemDesc.itemId = this.itemModel.id;
          this.loadSpecList();
          this.loadItemDesc();
        }
      });
    },
    onSaveSkuList() {
      this.$loading();
      mergeItemSkus(this.itemModel.id, this.data).then(() => {
        this.$message.success("保存成功");
        this.$loading().close();
        setTimeout(() => {
          this.$router.go(0);
        }, 500);
      });
    },
    loadSpecList() {
      getItemSpecList().then(data => {
        this.specNames = data;
        if (this.itemModel.id) {
          this.loadItemSkuList();
        } else {
          this.showSkuEditor = true;
        }
      });
    },
    fetchSkuGroup() {
      //获取可选的规格名
      return new Promise(resolve => {
        resolve(this.specNames);
      });
    },
    fetchSku(specId) {
      //获取指定规格的属性值
      return new Promise(resolve => {
        getSpecProps(specId, this.itemModel.id).then(data => {
          resolve(data);
        });
      });
    },

    createGroup(specName) {
      //创建规格
      return new Promise((resolve, reject) => {
        if (specName) {
          addItemSpec({ text: specName })
            .then(spec => {
              console.log("返回规格ID", spec.id);
              resolve(spec.id);
            })
            .catch(err => {
              reject(err);
            });
        } else {
          reject(new Error());
        }
      });
    },

    createSku(props) {
      console.log("props", props);
      return new Promise((resolve, reject) => {
        let specId = "";
        let specValues = props.data.map(specValue => {
          specId = props.id;
          return {
            specId: props.id,
            text: specValue,
            itemId: this.itemModel.id
          };
        });
        addSpecProps(specId, specValues)
          .then(resp => {
            console.log(resp);
            resolve(resp);
          })
          .catch(err => reject(err));
      });
    },
    onSkuChange(data) {
      // console.log(data);
    },
    handleChangeData(data) {
      this.data = data;
      console.log("table change", data);
    },
    loadItemSkuList() {
      getItemSkuList(this.itemModel.id).then(data => {
        console.log("data", data);
        this.showSkuEditor = true;
        this.specOptions = data.specTree;
        console.log("this.specOptions", this.specOptions);
        this.skuList = data.skuList;
      });
    },
    onInputChange(content) {
      this.itemDesc.descText = content;
      console.log(content);
    },
    onSaveItemDesc() {
      this.$loading();
      if (this.itemDesc.id) {
        // 更新
        updateItemDesc(this.itemDesc).then(() => {
          this.$message.success("保存成功");
          this.$loading().close();
          setTimeout(() => {
            this.$router.go(0);
          }, 500);
        });
      } else {
        // 保存
        // this.itemDesc.itemId = this.itemModel.id;
        saveItemDesc(this.itemDesc).then(() => {
          this.$message.success("保存成功");
          this.$loading().close();
          setTimeout(() => {
            this.$router.go(0);
          }, 500);
        });
      }
    },
    loadItemDesc() {
      this.$loading();
      getItemDesc(this.itemModel.id).then(data => {
        if (data) {
          this.itemDesc = data;
        }
        this.showEditor = true;
        this.$loading().close();
      });
    }
  },
  async mounted() {
    // this.categories = await this.loadAllCategories();
    // 加载商品信息
    this.loadBasicItem();
  }
};
</script>

<style scoped>
.item-prop {
}
.item-prop >>> .w-e-text-container {
  height: 600px !important; /*!important是重点，因为原div是行内样式设置的高度300px*/
}
</style>
